import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Table,
  Popconfirm,
  Divider,
  message,
  Select
} from 'antd';
import PropTypes from 'prop-types';
import Ellipsis from '@/components/Ellipsis';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import {transferOption } from "@/utils/common";
import DealerDetailModel from '@/components/Dealer/dealerDetailModel';
import DealerAddModel from './dealerAddModel';
import ResetPwdModel from '@/components/Dealer/DealerResetPwdModel';
import styles from '@/common/form.less';
// import { getDicByKey } from '@/components/common/PateoForm/utils/helper';
import { getDicByKey } from '@/support/common';
import UploadModal from './uploadModal';
import moment from 'moment';

const FormItem = Form.Item;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
  dealer: state.dealer,
}))
// @Form.create()
export default class log extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
    authButton: PropTypes.array,
  };
  state = {
    initLoading: false,
    visible: false,
    formValues: {},
    detailVisible: false,
    detailModelData: {},
    brandOptions:[],
    areaOptions:[],
    smallAreaOptions:[],
    add: {
      text: '新增',
      icon: 'plus',
    },
  };

  componentDidMount() {
    const { dispatch }= this.props;
    const { setFieldsValue } = this.refs.form;
   
    dispatch({
      type: 'common/queryListGet',
      payload: {url: '/dealer/brand'},
      callback: (data) => {
        this.setState({brandOptions: data});

        if(data && data.length>0){
          setFieldsValue({brandCode : data[0].brandCode});
          const newValus = {brandCode : data[0].brandCode}
          this.setState({
            formValues: newValus,
          });

          this.handleArea(data[0].brandCode);

          dispatch({
            type: 'dealer/fetchDealer',
            payload: {brandCode : data[0].brandCode}
          });
        }
      },
    });
  }

  handleInit = () => {
    this.setState({initLoading: true});
    this.props.dispatch({
      type: 'common/fetchGet',
      payload: {url: '/dealer/refreshDealer'},
      callback: (data) => {
        if(data.statusCode == 0){
          message.success('刷新成功!');
        }else{
          message.error(data.statusMessage);
        }
        this.setState({initLoading: false});
      },
    })
  }

  handleFormReset = () => {
    const { dispatch } = this.props;
    const {brandOptions} = this.state;
    const { form } = this.refs;
    form.resetFields();
    this.state.formValues = {};
    
    let params = {};

    if(brandOptions && brandOptions.length>0){
      form.setFieldsValue({brandCode : brandOptions[0].brandCode});
      params.brandCode = brandOptions[0].brandCode;

      const newValus = {brandCode : brandOptions[0].brandCode}
      this.setState({
        formValues: newValus,
      });
      this.handleArea(brandOptions[0].brandCode);
    }

    dispatch({
      type: 'dealer/fetchDealer',
      payload:params
    });
  };
  handleRemove = (code) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/queryListGet',
      payload: { url: '/dealer/del', code:code },
      callback: (data) => {
        if (data.statusCode === '0') {
          message.success('操作成功');
          this.handleFormReset();
        } else {
          message.error(data.statusMessage, 3);
          return;
        }
      },
    });
  };
  onRef = (ref) => {
    this.resetPwdModel = ref
  }
  resetPwd = (record) => {
    // this.refs.DealerResetPwd.showModal(record);
    this.resetPwdModel.showModal(record)
  };
  handleStandardTableChange = (pagination, filtersArg, sort) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const current = pagination.current - 1;
    const params = {
      page: current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sort.field) {
      params.sort = `${sort.field},${sort.order === 'descend' ? 'desc' : 'asc'}`;
    }
    dispatch({
      type: 'dealer/fetchDealer',
      payload: params,
    });
  };
  handleSearch = (fieldsValue) => {
    const { dispatch } = this.props;
    const { form } = this.refs;
    const newValus = { ...fieldsValue };
    this.setState({
      formValues: newValus,
    });
    dispatch({
      type: 'dealer/fetchDealer',
      payload: newValus,
    });
  };
  handleArea = (brandCode) => {
    const { dispatch } = this.props;
    const { form } = this.refs;
    this.setState({
      areaOptions:[],
      smallAreaOptions: [],
    });
    form.resetFields(['areaId','smallAreaId']);
    if(brandCode){
      dispatch({
        type: 'common/queryListGet',
        payload: { url: '/dealer/getareabybrand',brandId:brandCode },
        callback: (data) => {
          if(data) {
            this.setState({areaOptions: data});
          }
        },
      });
    }
  };
  handleSmallArea = (areaId) => {
    const { dispatch } = this.props;
    const { form } = this.refs;

    this.setState({
      smallAreaOptions: [],
    });
    form.resetFields(['smallAreaId']);
    if(areaId){
      dispatch({
        type: 'common/queryListGet',
        payload: { url: '/dealer/getsmallareabyarea',areaId:areaId },
        callback: (data) => {
          if(data) {
            this.setState({smallAreaOptions: data});
          }
        },
      });
    }
  };
  handleEdit = (selectedRows) => {
    this.refs.DealerAddModel.showModalEdit(selectedRows);
  };
  renderSimpleForm() {
    const { brandOptions,areaOptions,smallAreaOptions } = this.state;
    //const showCode = getDicByKey(this.context.dicData, 'vehicleTwoShowCode',"show");

    const formStyle = {
      style : {height : '80px'}
    };

    return (
      <Form onFinish={this.handleSearch} layout="inline" ref="form">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} {...formStyle}>
          <FormItem label="品牌" name="brandCode" rules={[{ required: true, message: '请选择' }]}>
            <Select
              allowClear
              placeholder="请选择品牌"
              getPopupContainer={triggerNode => triggerNode.parentNode}
              onChange={this.handleArea}
            >
              { transferOption(brandOptions,["brandCode","brandName"])}
            </Select>
          </FormItem>
          </Col>
          <Col md={8} sm={24} {...formStyle}>
          <FormItem label="大区" name="areaId">
            <Select
              allowClear
              placeholder="请选择大区"
              getPopupContainer={triggerNode => triggerNode.parentNode}
              onChange={this.handleSmallArea}
            >
              { transferOption(areaOptions,["code","descript"])}
            </Select>
          </FormItem>
          </Col>
          <Col md={8} sm={24} {...formStyle}>
          <FormItem label="小区" name="smallAreaId">
            <Select
              allowClear
              placeholder="请选择小区"
              getPopupContainer={triggerNode => triggerNode.parentNode}
            >
              { transferOption(smallAreaOptions,["code","descript"])}
            </Select>
          </FormItem>
          </Col>
          <Col md={8} sm={24} {...formStyle}>
          <FormItem label="经销商代码" name="code">
            <Input placeholder="请输入经销商代码" />
          </FormItem>
          </Col>
          <Col md={8} sm={24} {...formStyle}>
          <FormItem label="经销商名称" name="name">
            <Input placeholder="请输入经销商名称" />
          </FormItem>
          </Col>
          <Col md={8} sm={24} {...formStyle}>
          <span style={{float: 'right',marginBottom: 24}}>
          <Button type='primary' htmlType='submit'>查询</Button>
          <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
          </span>
          </Col>
          </Row>
      </Form>
    );
  }

  render() {
    const isAuth = true // this.context.authButton.includes('dealer-opt');
    const isDel = true // this.context.authButton.includes('dealer-del');
    const isEdit = true // this.context.authButton.includes('dealer-edit');
    const { dealer: { loading, data: { list, pagination } } } = this.props;

    const { initLoading } = this.state;
    const columns = [
      {
        title: '经销商代码',
        dataIndex: 'code',
      }, {
        title: '经销商名称',
        dataIndex: 'name',
        render: val => (
          <Ellipsis length={12} tooltip>{val}</Ellipsis>
        ),
      }, {
        title: '经销商简称',
        dataIndex: 'shortName',
        render: val => (
          <Ellipsis length={6} tooltip>{val}</Ellipsis>
        ),
      }, {
        title: '大区',
        dataIndex: 'areaId',
        render: (text, record) => (
          getDicByKey(this.context.dicData, `${record.brandId}area`, text)
        ),
      }, {
        title: '小区',
        dataIndex: 'smallAreaId',
        render: (text, record) => (
          getDicByKey(this.context.dicData, `${record.brandId}village`, text)
        ),
      }, {
        title: '经销商电话',
        dataIndex: 'phone',
      }, {
        title: '地址',
        dataIndex: 'address',
        render: val => (
          <Ellipsis length={12} tooltip>{val}</Ellipsis>
        ),
      }, {
        title: '展车数量',
        dataIndex: 'showCar',
      },{
        title:'经销商状态',
        dataIndex:'status',
        render: (text) => {
          return text != null ? getDicByKey(this.context.dicData, 'dealerStatus', text+"") : ''
        }
      },{
        title: '建立时间',
        dataIndex: 'openTime',
        render: (text) => {
          return text != null ? moment(text).format('YYYY-MM-DD HH:mm:ss') : ''
        }
      },{
        title: '操作',
        dataIndex: '操作',
        width: 140,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div>
              <span><a onClick={() => this.setState({ detailVisible: true, detailModelData: record })}>详情</a></span>
              {/*<Popconfirm title="确定要重置该经销商的账户密码吗?" onConfirm={() => this.resetPwd.bind(this)(record)}>*/}
              {/*  {isAuth ? <span> <Divider type="vertical" /><a>重置密码</a></span> : ''}*/}
              {/*</Popconfirm>*/}
            </div>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>,
    };
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <div className={styles.tableListOperator}>
              <span>
                {false && this.context.authButton.includes('dealer-init') ?
                <Button
                loading={initLoading}
                type="primary"
                className="ant-btn ant-btn-primary"
                onClick={ this.handleInit }
                >
                  初始化经销商数据
                </Button> : null}

                {false && this.context.authButton.includes('dealer-libraryImport') ?
                <Button
                type="primary"
                className="ant-btn ant-btn-primary"
                onClick={() => this.setState({uploadVisible: true}) }
                >
                  导入经销商主库信息
                </Button> : null
                }

              </span>
            </div>
            <Table
              size="default"
              loading={loading}
              rowKey={record => record.sid}
              dataSource={list}
              columns={columns}
              scroll={{x: 'max-content'}}
              pagination={paginationProps}
              onChange={this.handleStandardTableChange}
            />
            <DealerDetailModel
              changeVisible={() => this.setState({ detailVisible: false, detailModelData: {} })}
              visible={this.state.detailVisible}
              detailModelData={this.state.detailModelData}
              dispatch={this.props.dispatch}
            />
            <ResetPwdModel
              onRef={this.onRef}
              icon="plus"
              type="primary"
              dispatch={this.props.dispatch}
            />

            {/*<UploadModal*/}
            {/*  modalVisible={this.state.uploadVisible}*/}
            {/*  handleClose={() => { this.setState({ uploadVisible: false }) }}*/}
            {/*  title="导入经销商主库信息"*/}
            {/*/>*/}

          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
